package com.hadoop.controller;

import com.hadoop.common.Constants;
import com.hadoop.component.UploadFileBizComponent;
import com.hadoop.mybatis.po.User;
import com.hadoop.util.HadoopConnectionUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2017/10/13
 */
@RequestMapping(value = "/hadoop")
@Controller
public class StorageController {
    @Resource
    private UploadFileBizComponent uploadFileBizComponent;

    @RequestMapping(value = "/file/list")
    public String fileList(HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute("user");

        String key = Constants.UPLOAD_FILE_USERNAME + user.getUserName();
        model.addAttribute("fileList", uploadFileBizComponent.fileAttrVoList(key));
        return "/storage/list_file";
    }

    @RequestMapping(value = "/file/del")
    public String delFile(HttpServletRequest request, String fileName, Model model) throws IOException {
        User user = (User) request.getSession().getAttribute("user");

        String key = Constants.UPLOAD_FILE_USERNAME + user.getUserName();
        String msg = "删除失败";
        if (uploadFileBizComponent.delFile(key, fileName)) {
            File file = new File(uploadFileBizComponent.getFilePath() , fileName);
            if (file.delete()) {
                msg = "删除成功";
            }
            //删除hdfs中的文件
            FileSystem hdfs = HadoopConnectionUtils.getFileSystem();
            Path delPath = new Path("/data/"+fileName);
            hdfs.delete(delPath, false);
        }

        model.addAttribute("msg",msg);
        return "redirect:/hadoop/file/list";
    }
}
